//
//  FTextAarea4.swift
//  Hitching
//
//  Created by zhuxietong on 2021/5/24.
//  Copyright © 2021 蒋后福. All rights reserved.
//

import Foundation
import Eelay
import RxSwift
import RxCocoa




public class GrowInputNode:MoDisplayNode {
    public var miniHeight:CGFloat = 20{
        didSet{
            height = miniHeight
        }
    }
    var getSize:(_ size:CGSize) -> Void = {(e) in};
    var node:ASDisplayNode{
        didSet{
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
    required init() {
        self.node = ASDisplayNode(viewBlock: { () -> UIView in
            let view = NextGrowingTextView()
            return view
        })
        super.init()
        addLayoutRules()
    }
    var textView:UITextView?{
        return (node.view as? NextGrowingTextView)?.textView
    }
    var growView:NextGrowingTextView?{
        return node.view as? NextGrowingTextView
    }
    var height:CGFloat = 20{
        didSet{
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
    
    
    public override func addLayoutRules() {
        
        growView?.delegates.didChangeHeight = {[weak self] height in
            self?.height = height
        }
    }
  
    open override func specGetter() -> _Spec {

        let h = max(miniHeight, height)
        return .stack(["v",_grow(0),_shrink(0),&-.stretch], childs: [node[.>"\(h)"]])
    }
    open override func layoutDidFinish() {
        self.getSize(node.bounds.size)
    }
}
open class FTextArea4:FField,UITextViewDelegate{
    public var miniHeight:CGFloat = 20{
        didSet{
            textNode.miniHeight = miniHeight
        }
    }
    public let wordCountL = ASButtonNode()
    public let backNode = MoDisplayNode()

    public let textNode = GrowInputNode()
    

    open var maxNumberOfLines: Int {
        set{
            textNode.growView?.maxNumberOfLines = newValue

        }
        get{
            return textNode.growView?.maxNumberOfLines ?? 1
        }
    }

    open func checkWordCount(){

        let max = self.props.num_limit.max
        if max > 100000{
            wordCountL.alpha = 0
            return
        }
        
        let text = textNode.growView?.textView.text ?? ""

        self.wordCountL.ui.ntitle(title: "\(Int(text.count))/\(max)")
        wordCountL.backgroundColor = UIColor(shex: "#f0f0f0").alpha(0.8)
 
    }

    public var textView:NextGrowingTextView{
        return (textNode.view as? NextGrowingTextView) ?? NextGrowingTextView()
    }
    open override func didLoadProps() {
        textView.textView.text = "\(value)"
        textNode.growView?.textView.font = valueStyle.font
        lableNode.attributedText = _lable
        textNode.growView?.textView.attributedPlaceholder = placeholder.ui.font(font: placeHolderStyle.font).color(color: placeHolderStyle.color).left.astring
        checkWordCount()
    }
    
    open override func update(value:Any,edit:FEdit){
        self.value = value
        switch edit {
        case .input:
            break
        case .reply:
            didLoadProps()
            updateDispaly()
        default:
            didLoadProps()
            updateDispaly()
        }
    }
    
    open func changeText(text:String)  {
        self.update(value: text, edit: .input)
    }
    public let  bag = DisposeBag()
    open override func addLayoutRules() {
        super.addLayoutRules()

        wordCountL.ui.ncolor(color: ._weak).font(size: 12).padding(insets: [3,4]).set(radius: 8, width: nil, color: nil)
        backNode.bsui.background(color: ._tableBackground).set(radius: 6, width: TP.separatorHeight, color: ._separator)
    }
  
    open override func willLayoutRules() {
        super.willLayoutRules()
        textView.delegate = self
        textNode.backgroundColor = .clear
        maxNumberOfLines = 20
        textNode.textView?.rx.text.orEmpty.subscribe(onNext:{
            [weak self] t in
            
            self?.changeText(text: t)
            self?.checkWordCount()
        }).disposed(by: bag)
        
//        textNode.bsui.background(color: ._tableBackground).set(radius: 3, width: 1, color: UIColor._separator.alpha(0.3))
//        textView.addObserver(self, forKeyPath: "text", options: [.new,.old], context: nil)

    }
    
    open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

//        if text == "\n"{
//            textView.resignFirstResponder()
//            return false
//        }
//        let newStr = textView.text + text
//        if newStr.len > maxWordCount{
//            return false
//        }

        return true

    }
    public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        return true
    }
    
    open var maxWordCount:Int{
        return props.num_limit.max
    }
    
    open func textViewDidChange(_ textView: UITextView) {
//
//        if textView.text.count > maxWordCount {
//
//            //获得已输出字数与正输入字母数
//            let selectRange = textView.markedTextRange
//
//            //获取高亮部分 － 如果有联想词则解包成功
//            if let selectRange = selectRange {
//                let position =  textView.position(from: (selectRange.start), offset: 0)
//                if (position != nil) {
//                    return
//                }
//            }
//
//            guard let textContent = textView.text else {
//                return
//            }
//
//            //截取200个字
//            if textContent.len > maxWordCount {
////                let index = textContent.index((textContent.startIndex)!, offsetBy: maxWordCount)
//                let str = textContent.sub(from: 0, end: (maxWordCount - 1))
//                textView.text = str
//            }
//        }
//        update(value: textView.text ?? "", edit: .input)
//
//        checkWordCount()

   }

    
    open override func specGetter() -> _Spec {
        let spec = _Spec.inset([], [0], child: .stack(["v|3",&-.stretch], childs: [
            textNode.Spec.addOver(.stack(["v",&-.stretch,_justfy(.space_between)], childs: [
                .stack([], childs: []),
                .stack(["h",_justfy(.space_between)], childs: [
                    .stack([], childs: []),
                    .if(maxWordCount < 10000, spec: _Spec.inset([], [4], child: wordCountL.Spec))
                ])
            ]))
        ])).addBack(backNode.Spec)
        return .stack(["v|8",&-.stretch], childs: [
            .if(label.len > 0, spec: lableNode.Spec),
            spec
        ])
    }
}
